package com.easyxu.kubernetes.filebrowser.service;

import com.easyxu.kubernetes.filebrowser.service.dto.DirectoryQryCmd;
import com.easyxu.kubernetes.filebrowser.service.dto.FileDownloadCmd;
import com.easyxu.kubernetes.filebrowser.service.dto.data.DirectoryDto;
import com.easyxu.kubernetes.filebrowser.service.executor.DeploymentQryCmdExe;
import com.easyxu.kubernetes.filebrowser.service.executor.DirectoryQryCmdExe;
import com.easyxu.kubernetes.filebrowser.service.executor.FileDownloadCmdExe;
import com.easyxu.kubernetes.filebrowser.service.executor.NamespaceQryCmdExe;
import com.easyxu.kubernetes.filebrowser.service.executor.PodQryCmdExe;
import io.kubernetes.client.openapi.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class KubernetesService {

    @Autowired
    private NamespaceQryCmdExe namespaceQryCmdExe;
    @Autowired
    private DeploymentQryCmdExe deploymentQryCmdExe;
    @Autowired
    private PodQryCmdExe podQryCmdExe;
    @Autowired
    private DirectoryQryCmdExe directoryQryCmdExe;
    @Autowired
    private FileDownloadCmdExe fileDownloadCmdExe;

    public List<String> getAllNamespace(){
        return namespaceQryCmdExe.execute();
    }

    public List<String> getDeploymentByNamespace(String namespace){
        return deploymentQryCmdExe.execute(namespace, null)
                .stream()
                .map(i->i.getMetadata().getName())
                .collect(Collectors.toList());
    }

    public List<String> getPodByNamespaceAndDeployment(String namespace, String deployment) throws ApiException {
        return podQryCmdExe.execute(namespace, deployment)
                .stream()
                .map(item->item.getMetadata()
                        .getName()).collect(Collectors.toList());
    }

    public List<DirectoryDto> filebrowser(DirectoryQryCmd cmd) throws IOException, ApiException {
        return directoryQryCmdExe.execute(cmd);
    }

    public InputStream getPodFileStream(FileDownloadCmd cmd) throws IOException, ApiException {
        return fileDownloadCmdExe.execute(cmd);
    }
}
